package com.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import com.vo.Student;
import java.util.List;

@Controller
public class ShowStudentController {

    @RequestMapping("login")
    public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {

        if ("winner".equals(username) && "123".equals(password)) {
            List<Student> students = new ArrayList<>();
            students.add(new Student("Winner", 200));
            students.add(new Student("Loser", 220));
            students.add(new Student("Daniu", 210));

            session.setAttribute("students", students);
            session.setAttribute("loggedIn", true);
            return new ModelAndView("show.jsp");
        } else {
            session.setAttribute("error","账号或者密码错误");
            return new ModelAndView("index.jsp");
        }
    }

    @RequestMapping(value = "/showJson", method = RequestMethod.GET)
    public ModelAndView showJson(HttpSession session) throws JsonProcessingException {
//        Boolean loggedIn = (Boolean) session.getAttribute("loggedIn");
//        if (loggedIn == null || !loggedIn) {
//            return new ModelAndView("redirect:/index.jsp");
//        }
        List<Student> students = (List<Student>) session.getAttribute("students");

        ObjectMapper objectMapper = new ObjectMapper();
        String studentsJson = objectMapper.writeValueAsString(students);

        ModelAndView mav = new ModelAndView("showJson.jsp");
        mav.addObject("studentsJson", studentsJson);
        return mav;
    }
}